﻿Imports OpenNETCF.Desktop.Communication
Imports System.IO

Partial Public Class ucSynchronise
    Dim FileFound As Integer
    Dim SearchCriteria As String = My.Settings.SearchCriteria
    Dim oRapi As RAPI
    Dim localLocation As String = My.Settings.localLocation
    Dim remoteLocation As String = My.Settings.remoteLocation
    Dim retainFilesonReader As Boolean = My.Settings.retainFilesonReader
    Dim dbRFIDScanTable As ATSDataClassesDataContext = New ATSDataClassesDataContext
    Dim recordCtr As String = 0
    Dim remotefileCount As New Integer

    Private Sub btnExtract_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnExtract.Click
        listboxNotonDatabase.Items.Clear()
        oRapi = New RAPI
        imgDeviceError.Visibility = Windows.Visibility.Hidden

        PBar.Visibility = Windows.Visibility.Visible
        Dim duration As Duration = New Duration(TimeSpan.FromSeconds(20))
        Dim doubleAnimation As Animation.DoubleAnimation = New Animation.DoubleAnimation(200.0, duration)
        PBar.BeginAnimation(ProgressBar.ValueProperty, doubleAnimation)
        PBarimgFilesFound.BeginAnimation(ProgressBar.ValueProperty, doubleAnimation)
        PBarimgUpdateDatabase.BeginAnimation(ProgressBar.ValueProperty, doubleAnimation)


        If IsDeviceConnected() Then
            If oRapi.Connected Then
                imgDeviceOk.Visibility = Windows.Visibility.Visible
                PBar.Visibility = Windows.Visibility.Hidden
                imgDeviceError.Visibility = Windows.Visibility.Hidden
                If FilesFoundOnDevice() Then
                    If remotefileCount > 0 Then
                        imgFilesFoundOk.Visibility = Windows.Visibility.Visible
                        PBarimgFilesFound.Visibility = Windows.Visibility.Hidden
                        imgFilesFoundError.Visibility = Windows.Visibility.Hidden
                        If retainFilesonReader Then
                            removeFilesFromDevice()
                        End If
                    Else
                        imgFilesFoundOk.Visibility = Windows.Visibility.Hidden
                        imgFilesFoundError.Visibility = Windows.Visibility.Visible
                        PBarimgFilesFound.Visibility = Windows.Visibility.Hidden
                    End If
                    PBarimgUpdateDatabase.Visibility = Windows.Visibility.Visible
                    imgUpdateDatabaseError.Visibility = Windows.Visibility.Hidden
                    imgUpdateDatabaseOk.Visibility = Windows.Visibility.Hidden
                    UpdateRFIDData()
                Else
                    imgFilesFoundOk.Visibility = Windows.Visibility.Hidden
                    imgFilesFoundError.Visibility = Windows.Visibility.Visible
                    PBarimgFilesFound.Visibility = Windows.Visibility.Hidden

                    imgUpdateDatabaseError.Visibility = Windows.Visibility.Visible
                    imgUpdateDatabaseOk.Visibility = Windows.Visibility.Hidden
                    PBarimgUpdateDatabase.Visibility = Windows.Visibility.Hidden
                End If

            Else
                imgDeviceOk.Visibility = Windows.Visibility.Hidden
                imgDeviceError.Visibility = Windows.Visibility.Visible
                PBar.Visibility = Windows.Visibility.Hidden

                PBarimgUpdateDatabase.Visibility = Windows.Visibility.Visible
                imgUpdateDatabaseError.Visibility = Windows.Visibility.Hidden
                imgUpdateDatabaseOk.Visibility = Windows.Visibility.Hidden
                UpdateRFIDData()
            End If
        Else
            imgDeviceOk.Visibility = Windows.Visibility.Hidden
            imgDeviceError.Visibility = Windows.Visibility.Visible
            PBar.Visibility = Windows.Visibility.Hidden

            imgFilesFoundOk.Visibility = Windows.Visibility.Hidden
            imgFilesFoundError.Visibility = Windows.Visibility.Visible
            PBarimgFilesFound.Visibility = Windows.Visibility.Hidden

            imgUpdateDatabaseError.Visibility = Windows.Visibility.Visible
            imgUpdateDatabaseOk.Visibility = Windows.Visibility.Hidden
            PBarimgUpdateDatabase.Visibility = Windows.Visibility.Hidden
        End If
        If listboxNotonDatabase.Items.Count > 0 Then
            spNotonDatabase.Visibility = Windows.Visibility.Visible
        End If
    End Sub

    Private Sub ucSynchronise_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded

    End Sub

    Private Function IsDeviceConnected() As Boolean
        Try
            If oRapi.DevicePresent Then
                oRapi.Connect()
                If oRapi.Connected Then
                    Return True
                End If
            End If
        Catch ex As Exception
            If MsgBox("Cannot connect to the device. " & ex.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Device not found") = MsgBoxResult.Yes Then
                Return True
            End If
            Return False
        End Try
        If MsgBox("Cannot connect to the device." & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Device not found") = MsgBoxResult.Yes Then
            Return True
        End If
        Return False
    End Function

    Private Function FilesFoundOnDevice() As Boolean
        Dim files As Boolean = False
        Dim di As DirectoryInfo

        Try
            remotefileCount = 0
            If Not oRapi.EnumFiles(remoteLocation & "*.txt") Is Nothing Then
                remotefileCount = oRapi.EnumFiles(remoteLocation & "*.txt").Count
            End If
            If remotefileCount > 0 Then
                Try
                    di = New DirectoryInfo(localLocation)
                    If Not di.Exists Then
                        di.Create()
                    End If
                    For int As Integer = 0 To remotefileCount - 1
                        Try
                            oRapi.CopyFileFromDevice(localLocation & oRapi.EnumFiles(remoteLocation & "*.txt").Item(int).FileName, remoteLocation & oRapi.EnumFiles(remoteLocation & "*.txt").Item(int).FileName, True)
                            files = True
                        Catch RAPIerr As RAPIException
                            If MsgBox(RAPIerr.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed") = MsgBoxResult.Yes Then
                                files = True
                            End If
                        Catch ex As Exception
                            If MsgBox(ex.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed") = MsgBoxResult.Yes Then
                                files = True
                            End If
                        End Try
                    Next
                Catch ex As Exception
                    If MsgBox(ex.ToString & remoteLocation.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed") = MsgBoxResult.Yes Then
                        files = True
                    End If
                End Try
            Else
                If MsgBox("No files found under reader directory " & remoteLocation.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed") = MsgBoxResult.Yes Then
                    files = True
                End If
            End If
        Catch RAPIerr As RAPIException
            If MsgBox(RAPIerr.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed.") = MsgBoxResult.Yes Then
                files = True
            End If
        Catch ex As Exception
            If MsgBox("No files found at reader location: " & remoteLocation.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed") = MsgBoxResult.Yes Then
                files = True
            End If
        Finally
        End Try
        oRapi.Disconnect()
        Return files
    End Function

    Private Sub removeFilesFromDevice()
        Try
            oRapi.Connect()
            If oRapi.Connected Then
                Dim fileCount As Integer = oRapi.EnumFiles(remoteLocation & "*.txt").Count
                For int As Integer = 0 To fileCount - 1
                    Try
                        oRapi.DeleteDeviceFile(remoteLocation & oRapi.EnumFiles(remoteLocation & "*.txt").Item(0).FileName)
                    Catch RAPIerr As RAPIException
                        MsgBox(RAPIerr.ToString, MsgBoxStyle.Information, "Failed to remove files. Reconnect device and try again")
                    End Try
                Next
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Information, "Failed to remove files. Reconnect device and try again")
        End Try
        oRapi.Disconnect()
    End Sub

    Private Sub UpdateRFIDData()
        recordCtr = 0
        SearchCriteria = String.Empty

        Try
            Dim path As String = localLocation
            Dim CriteriaPath, files, filename As String

            CriteriaPath = path.Substring(0, path.LastIndexOf("\"))

            If SearchCriteria.Length = 0 Then
                SearchCriteria = "*.txt"
            Else
                SearchCriteria = path.Substring(path.LastIndexOf("\") + 1)
            End If

            For Each files In Directory.GetFiles(CriteriaPath, SearchCriteria)
                filename = Mid(files, localLocation.Length + 1, files.Length - localLocation.Length + 1)
                Dim parser As New FileIO.TextFieldParser(files)
                parser.TextFieldType = FileIO.FieldType.Delimited
                parser.SetDelimiters(" ")
                While Not parser.EndOfData
                    parser.ReadFields()
                End While
                parser.Close()
                parser = New FileIO.TextFieldParser(files)
                parser.TextFieldType = FileIO.FieldType.Delimited
                parser.SetDelimiters(" ")

                Dim currentRow() As String
                Dim fldCtr As Integer
                While Not parser.EndOfData
                    fldCtr = 1
                    Try
                        currentRow = parser.ReadFields()
                        Dim currentField As String
                        For Each currentField In currentRow
                            If fldCtr = 2 Then
                                Dim rfidNumber As String = Mid(currentRow(1), currentRow(1).Length - 9, 10)
                                Dim rfidScanDate As Date = CDate(Mid(filename, 1, 4) & "/" & Mid(filename, 5, 2) & "/" & Mid(filename, 7, 2))
                                Dim RFIDDateScanned = From RFIDTable In dbRFIDScanTable.RFIDScanHistories.Where(Function(o) o.RFIDNum = rfidNumber And o.DateScanned = rfidScanDate)
                                If RFIDDateScanned.Count = 0 Then
                                    Dim RFIDScannedTable As New RFIDScanHistory
                                    With RFIDScannedTable
                                        .DateScanned = rfidScanDate
                                        .RFIDNum = rfidNumber
                                    End With
                                    dbRFIDScanTable.RFIDScanHistories.InsertOnSubmit(RFIDScannedTable)
                                End If
                                Dim itemsTable = From ATSItemsTable In dbRFIDScanTable.MainAssetsTables _
                                                 Where ATSItemsTable.RFIDno = rfidNumber
                                If itemsTable.Count > 0 Then
                                    With itemsTable.First
                                        .LastScanDate = rfidScanDate
                                    End With
                                Else
                                    If Not listboxNotonDatabase.Items.Contains(rfidNumber) Then
                                        listboxNotonDatabase.Items.Add(rfidNumber)
                                        listboxNotonDatabase.Items.Refresh()
                                    End If
                                    End If
                                    dbRFIDScanTable.SubmitChanges()

                                    'Label1.Text &= currentRow(1) & ControlChars.Lf
                                    recordCtr += 1
                                End If
                            fldCtr += 1
                        Next
                    Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                        MsgBox("Line " & ex.Message & _
                        "is not valid and will be skipped.")
                    End Try
                End While
                parser.Close()

                FileFound += 1
                If File.Exists(files) Then
                    File.Move(files, Mid(files, 1, files.Length - 3) & Format(Now(), "ddMMyyhhmmss"))
                Else
                    File.Move(files, Mid(files, 1, files.Length - 3) & "old")
                End If

            Next

            imgUpdateDatabaseError.Visibility = Windows.Visibility.Hidden
            imgUpdateDatabaseOk.Visibility = Windows.Visibility.Visible
            PBarimgUpdateDatabase.Visibility = Windows.Visibility.Hidden

            lblNumberofRecordsProcessed.Content = recordCtr
        Catch ex As Exception
            MsgBox("Please check format of reader files.")
            imgUpdateDatabaseError.Visibility = Windows.Visibility.Visible
            imgUpdateDatabaseOk.Visibility = Windows.Visibility.Hidden
            PBarimgUpdateDatabase.Visibility = Windows.Visibility.Hidden
        End Try
    End Sub
End Class
